#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

### BEGIN INIT INFO
# Provides:          cloudstack-ipallocator
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# description:       Cloud IP address allocation
### END INIT INFO

# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well

. /lib/lsb/init-functions
. /etc/rc.status

# set environment variables

SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"

unset OPTIONS
[ -r @SYSCONFDIR@/default/"$SHORTNAME" ] && source @SYSCONFDIR@/default/"$SHORTNAME"
DAEMONIZE=@BINDIR@/@PACKAGE@-daemonize
PROG=@BINDIR@/@PACKAGE@-external-ipallocator.py
OPTIONS=8083

start() {
        log_daemon_msg $"Starting $PROGNAME" "$SHORTNAME"
	if [ -s "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
	      log_progress_msg "apparently already running"
	      log_end_msg 0
	      exit 0
	fi
	if hostname --fqdn >/dev/null 2>&1 ; then
		true
	else
		log_failure_msg "The host name does not resolve properly to an IP address.  Cannot start $PROGNAME"
		log_end_msg 1
		exit 1
	fi

	if start-stop-daemon --start --quiet \
		--pidfile "$PIDFILE" \
		--exec "$DAEMONIZE" -- -n "$SHORTNAME" -p "$PIDFILE" -l "$LOGFILE" "$PROG" $OPTIONS
		RETVAL=$?
	    then
		rc=0
		sleep 1
		if ! kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
		    log_failure_msg "$PROG failed to start"
		    rc=1
		fi
	else
		rc=1
	fi

	if [ $rc -eq 0 ]; then
		log_end_msg 0
	else
		log_end_msg 1
		rm -f "$PIDFILE"
	fi
}

stop() {
	echo -n $"Stopping $PROGNAME" "$SHORTNAME"
	start-stop-daemon --stop --quiet --oknodo --pidfile "$PIDFILE"
	log_end_msg $?
	rm -f "$PIDFILE"
}


# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
        status_of_proc -p "$PIDFILE" "$PROG" "$SHORTNAME"
	RETVAL=$?
	;;
  restart)
	stop
	sleep 3
	start
	;;
  *)
	echo $"Usage: $SHORTNAME {start|stop|restart|status|help}"
	RETVAL=3
esac

exit $RETVAL
